/*
 * Copyright 2002-2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.easyframework.support.auditing.interceptor;

import java.io.Serializable;
import java.lang.reflect.Type;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.easyframework.support.util.CommonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.support.AopUtils;

/**
 * @author Amila Domingo
 *
 */
public class AuditInterceptor extends AuditAspectSupport implements MethodInterceptor, Serializable {

	private Logger logger = null;

	public Object invoke(MethodInvocation invocation) throws Throwable {

		// Work out the target class: may be <code>null</code>.
		// The LogAttribute should be passed the target class
		// as well as the method, which may be from an interface.
		Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);

		logger = LoggerFactory.getLogger(targetClass);

		// If the log attribute is null, the method is non-loggable.
		final AuditAttribute logAttribute = getLogAttributeSource().getLogAttribute(invocation.getMethod(), targetClass);

		Object retVal = null;
		try {
			retVal = invocation.proceed();
		} catch (Throwable ex) {
			throw ex;
		} finally {
			if (invocation.getMethod().getName().startsWith(logAttribute.getPattern()))
			{
				insertAuditEntry(targetClass, invocation, retVal);
			}
		}

		return retVal;
	}

	private void insertAuditEntry(Class<?> targetClass, MethodInvocation invocation, Object retVal) {
		final StringBuilder message = new StringBuilder();

		message.append("Completed executing " + invocation.getMethod().getName() + ".");

		if (CommonUtil.isNotNullOrEmpty(retVal)) {
			final Type paramType = invocation.getMethod().getGenericReturnType();

			message.append(" Following was returned: [type: " + paramType + ", value: " + retVal + "]");
		}

		logger.info(message.toString());
	}
}